import { toast, promptBox, cacheTools } from 'nc-lightapp-front';
import deepCopy from "../../../../hrpub/common/utils/deep-copy";
import {saveValidate} from "../../../public/functions/unit";
export default class FormAction {
	constructor(comp) {
		this.comp = comp;
	}

	didMount = () => {};

	// 进入到新增页面
	toAddPage = async () => {
		const { props, action } = this.comp;
		const { form, dispatch, exam } = props;
		// 清空数据
		form.EmptyAllFormValue('card');
		try {
			let res = await dispatch({
				type: 'exam/regApplyAddAction',
				payload: {
					postData: {
						pk_org: exam.refValue.refpk,
						area_code: 'card',
						page_code: exam.config.pagecode,
						probationType: exam.probationType === '3' ? '' : exam.probationType
					}
				}
			});
			if (res.success) {
				form.setFormStatus('card', 'add');
				action.btnAct.buttonTool(props, false);
				dispatch({
					type: 'exam/update',
					payload: {
						cardMode: true,
						editState: true,
						page: 'add',
						type: res.data.formData.card.rows[0].values.probation_type.value
					}
				});

				// 卡片页禁用显示方法
				action.table.functionStateTool(res.data);

				// 是否禁用编码
				if (res.data.isBillCodeEditable === true) {
					form.setFormItemsDisabled('card', { bill_code: false });
				} else {
					form.setFormItemsDisabled('card', { bill_code: true });
				}

				// 展开子列表
				form.openArea('card','psninfo');
				form.openArea('card','oldinfo');
				form.openArea('card','newinfo');
				form.openArea('card','execinfo');
				form.openArea('card','audit_info');
				form.openArea('card','table_end_info');
				if (res.data.formData) {
					form.setAllFormValue({ card: res.data.formData.card });
				}
			}
		} catch (e) {
			throw e;
		}
		// this.formBeforeEdit()
    };

	// 保存数据
	saveItemState = async () => {
		const { props, action } = this.comp;
		const { form, dispatch, exam, cardPagination, button } = props;
		let formData = form.getAllFormValue('card');
        let billType = ["psninfo","oldinfo","newinfo","execinfo","audit_info","table_end_info"];
        saveValidate(props, 'card', 'card', billType, 'extcard', null).then(async ()=>{
            try {
                let res = await dispatch({
                    type: 'exam/regApplySaveAction',
                    payload: {
                        postData: {
                            opera_code: exam.page === 'add' ? '1' : '2',
                            area_code: 'card',
                            page_code: exam.config.pagecode,
                            formData: formData,
                            pk_org: exam.refValue.refpk
                        }
                    }
                });
                if (res.success) {
                    form.setAllFormValue({ card: res.data.formData.card });
                    form.setFormStatus('card', 'browse');

                    //修改按钮状态
                    action.btnAct.functionSure(props, true, true);

                    button.setButtonsVisible({
                        edit: true
                    });

                    this.backButtonstate(false);

                    if (exam.page === 'add') {
                        // 如果为新增卡片页面，设置卡片翻页
                        exam.allpks.push(res.data.formData.card.rows[0].values.pk_hi_regapply.value);

                        cacheTools.set('allpks', exam.allpks);
                        dispatch({
                            type: 'exam/update',
                            payload: {
                                allpks: exam.allpks
                            }
                        });

                        cardPagination.setCardPaginationId({
                            id: res.data.formData.card.rows[0].values.pk_hi_regapply.value,
                            status: 1
                        });
                    }

                    if (res.data && res.data.tip === true) {
                        toast({ color: 'info', content: `${exam.json['gx6008-000030']}!${res.data.tipMsg}` });
                    } else {
												// 保存成功
												toast({ color: 'success', content: exam.json['gx6008-000030'] });
										}

                    this.approveButton();
                    dispatch({
                        type: 'exam/update',
                        payload: {
                            page: '',
                            billid: res.data.formData.card.rows[0].values.pk_hi_regapply.value
                        }
                    });
                }
            } catch (e) {
                throw e;
            }
        });
	};
	// 表单编辑前
	formBeforeEdit = async (platFormProps, formId, key = 'pk_psnjob', value, data) => {
		const { props } = this.comp;
		const { exam, dispatch, form, meta } = props;
		try {
			let template = props.meta.getMeta();
			let isRefer = false;
			[
				'card',
				'card_batch',
				'psninfo',
				'oldinfo',
				'newinfo',
				'execinfo',
				'table_end_info',
				'audit_info',
				'psninfo_batch',
				'newinfo_batch',
				'execinfo_batch',
				'table_end_info_batch',
				'query'
			].map(formId => {
				template[formId].items.map((item) => {
					if (item.attrcode === key && item.queryCondition) {
						isRefer = item.itemtype === 'refer'; 
					}
				});
			});
			if (!isRefer) return true;
			let postData = {
				key: key,
				pk_org: exam.refValue.refpk
			};

			// 判断是否为卡片模式
			exam.cardMode === true
				? (postData.formData = form.getAllFormValue('card'))
				: (postData.formData = form.getAllFormValue('card_batch'));

			let res = await dispatch({
				type: 'exam/formEditBefore',
				payload: {
					postData: postData
				}
			});
			if (res.data && res.data.refParam) {
				// 给每个区域的每一项添加编辑前事件
				[
					'card',
					'card_batch',
					'psninfo',
					'oldinfo',
					'newinfo',
					'execinfo',
					'table_end_info',
					'audit_info',
					'psninfo_batch',
					'newinfo_batch',
					'execinfo_batch',
					'table_end_info_batch',
					'query'
				].map((item) => {
					template[item].items.map((item) => {
						if (item.attrcode === key) {
							Object.assign(
								item.queryCondition || {},
								{
									pk_org: exam.refValue.refpk
								},
								res.data.refParam || {},
								{ probationType: exam.probationType === '3' ? '' : exam.probationType }
							);
						}
					});
				});
			}

			await new Promise((resolve, reject) => {
				meta.setMeta(template, resolve);
			});
		} catch (e) {
			throw e;
		}
		return true;
	};

	// 表单编辑后
	formAfterEdit = (platFormProps, formId, key, value, preVal) => {
		const { props } = this.comp;
		const { exam, dispatch, form, meta } = props;
		let area_code = null;
		let formData = null;

		if (exam.cardMode === true) {
			area_code = 'card';
			formData = form.getAllFormValue(area_code);
		} else {
			area_code = 'card_batch';
			formData = form.getAllFormValue(area_code);
		}

		let postData = {
			key: key,
			area_code: area_code,
			formData: formData,
			page_code: exam.cardMode === true ? exam.config.pagecode : `${exam.config.appcode}batchAdd`,
			pk_org: exam.refValue.refpk,
			probationType: exam.type
		};

		dispatch({
			type: 'exam/formEditAfter',
			payload: {
				postData: postData
			}
		}).then((res) => {
			if (res.data && res.data.formData) {
				res.data.visible && form.setFormItemsVisible(area_code, res.data.visible);
				res.data.disable && form.setFormItemsDisabled(area_code, res.data.disable);
				res.data.required && form.setFormItemsRequired(area_code, res.data.required);

				if (exam.cardMode === true) {
					form.setAllFormValue({ card: res.data.formData.card });
				} else {
					form.setAllFormValue({ card_batch: res.data.formData.card_batch });
				}
			}
		});
	};

	// 返回主表页面
	goToBackMainPage = () => {
		const { props, action } = this.comp;
		const { exam, dispatch } = props;
		if(exam.widget){
			dispatch({
				type: 'exam/update',
				payload: {
					cardMode: false
				}
			});
			button.setButtonsVisible({
				add:false,
				edit: false,
				del: false,
				commit: false,
				aux_function: false, //辅助功能
				recover: false,
				search: false,
				refresh: false,
				execute: false, //执行
				print: false, //打印
				organization: false, //编辑情况
				sendMsg: false, //发送通知
				out: false ,//输出
				batchAdd: false,
				save:false,
				cancel:false
			});
			this.pubSub.publish('getWidgetTableData');
		}else{
			this.backButtonstate(false);
			dispatch({
				type: 'exam/update',
				payload: {
					cardMode: false
				}
			});
			this.pubSub.publish('initData');
			action.btnAct.buttonTool(props, true);
		}

	};

	backButtonstate = (flag) => {
		const { props } = this.comp;
		const { button } = props;
		button.setButtonDisabled({
			edit: flag,
			del: flag,
			commit: flag,
			aux_function: flag, //辅助功能
			recover: flag,
			search: flag,
			refresh: flag,
			execute: flag, //执行
			print: flag, //打印
			organization: flag, //编辑情况
			sendMsg: flag, //发送通知
			out: flag //输出
		});
	};
	// 从审批页面进入的按钮状态
	approveButton = () => {
		const { props, action } = this.comp;
		const { exam, button } = props;
		if (this.comp.props.exam.fromApprove === true) {
			console.log(exam.fromApprove)
			button.setButtonsVisible({
				edit: true,
				del: false,
				commit: false,
				aux_function: true, //辅助功能
				recover: false,
				search: false,
				add: false,
				refresh: true,
				execute: true, //执行
				print: true, //打印
				organization: true, //编辑情况
				sendMsg: false, //发送通知
				out: true, //输出
				psncard: true, //联查卡片,
				file: true
			});
			button.setButtonDisabled({
				execute: false, //执行
				organization: false,
				out: false,
				print: false,
				refresh: false,
				edit: false,
				file: false
			});
		}
	};
	// 查询单条数据
	oneAction = async (billid) => {
		const { props, action } = this.comp;
		const { exam, dispatch, form, cardPagination, button } = props;
		const { createCardPagination } = cardPagination;

		cardPagination.setCardPaginationId({ id: billid, status: 1 });
		button.setButtonsVisible({
			edit: true,
			batchAdd: false,
			search: false,
			file: true
		});

		if (!billid) {
			this.backButtonstate(true);
			return;
		}
		// 从审批页面进入的按钮状态
		this.approveButton();
		let postData = {
			area_code: 'card',
			pk_org: exam.refValue.refpk,
			billid: billid,
			page_code: exam.config.pagecode
		};
		try {
			let res = await dispatch({
				type: 'exam/oneAction',
				payload: {
					postData: postData
				}
			});
			if (res.success) {
				action.table.functionStateTool(res.data);

				form.setAllFormValue({ card: res.data.formData.card });

				dispatch({
					type: 'exam/update',
					payload: {
						billid: res.data.formData.card.rows[0].values.pk_hi_regapply.value
					}
				});

				form.openArea('card','psninfo');
				form.openArea('card','oldinfo');
				form.openArea('card','newinfo');
				form.openArea('card','execinfo');
				form.openArea('card','audit_info');
				form.openArea('card','table_end_info');
			}
		} catch (e) {
			throw e;
		}
	};

	//翻页

	cardPageInfo = (props, billid) => {
		this.oneAction(billid);
	};

	//修改
	editAction = () => {
		const { props, action } = this.comp;
		const { exam, dispatch, form } = props;
		action.table.editFunc();
	};
}
